package com.china08.yxyapi.api.manage.tec.teaching.lecture.res;

import java.io.File;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.db.res.YxyResResource;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.db.YxyResResourceRepository;
import com.china08.yxyapi.util.YXGetVideoInfoUtil;
import com.china08.yxyapi.util.YxyResUtil;

/**
 * 老师上传备授课 资源（文件上传）
 * 
 * @author renruihu
 *
 */
@CrossOrigin
@RestController
public class UploadResController extends YxyApiBaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(UploadResController.class);

    @Value("${weike.storage.upload.video}")
    private String uploadBasePath;

    @Autowired
    private YxyResResourceRepository resourceRepository;

    @Autowired
    private YXGetVideoInfoUtil yXGetVideoInfoUtil;

    @RequestMapping(value = "/api_yw/manage/tec/teaching/lecture/upload/file", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Object process(HttpServletRequest request, HttpServletResponse response, @RequestPart MultipartFile file,
            RespModel respModel) throws Exception {

        String md5 = DigestUtils.md5Hex(file.getBytes());
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        Assert.isTrue(!StringUtils.equals("exe", extension) || !StringUtils.equals("zip", extension)
                || !StringUtils.equals("rar", extension), "不支持exe、压缩包格式！");

        List<YxyResResource> md5OrderByUploadTimeAsc = resourceRepository.findByMd5OrderByUploadTimeAsc(md5);
        YxyResResource rYxyResResource = null;
        if (CollectionUtils.isNotEmpty(md5OrderByUploadTimeAsc)) {
            rYxyResResource = md5OrderByUploadTimeAsc.get(0);
        }
        String location = "";
        Long size = 0l;
        Integer duration = 0;
        if (rYxyResResource != null) {
            location = rYxyResResource.getLocation();
            size = Long.valueOf(rYxyResResource.getFileSize());
            if (extension.equals("mp4") || extension.equals("avi") || extension.equals("rmvb")
                    || extension.equals("wmv") || extension.equals("mpeg") || extension.equals("mov")
                    || extension.equals("3gp") || extension.equals("MP4")) {
                duration = rYxyResResource.getDuration();
                if (duration != 0) {
                    Long duration1 = yXGetVideoInfoUtil.getDuration(uploadBasePath + location) / 1000;
                    if (duration1 != null) {
                        duration = Integer.valueOf(duration1 + "");
                    }
                }
            }
            rYxyResResource.setDuration(duration);
            resourceRepository.save(rYxyResResource);
        } else {
            String path = YxyResUtil.getPath();
            String savePath = uploadBasePath + path;
            File sf = new File(savePath);
            String realPath = sf.getPath() + File.separator + md5.substring(0, 2) + File.separator + md5 + "."
                    + extension;
            FileUtils.forceMkdir(sf);
            FileUtils.writeByteArrayToFile(new File(realPath), file.getBytes());
            location = path + "/" + md5.substring(0, 2) + "/" + md5 + "." + extension;
            if (extension.equals("mp4") || extension.equals("avi") || extension.equals("rmvb")
                    || extension.equals("wmv") || extension.equals("mpeg") || extension.equals("mov")
                    || extension.equals("3gp") || extension.equals("MP4")) {
                Long duration1 = yXGetVideoInfoUtil.getDuration(uploadBasePath + location) / 1000;
                if (duration1 != null) {
                    duration = Integer.valueOf(duration1 + "");
                }
            }
            size = file.getSize();
        }
        respModel.md5 = md5;
        respModel.location = location;
        respModel.size = size;
        respModel.extension = extension;
        respModel.duration = duration;
        return respModel;
    }

    protected static class RespModel extends YxyApiRespModel {
        public String md5;
        public String location;
        public long size;
        public String extension;
        public Integer duration;
    }

}
